<?php defined('SYSPATH') or die('No direct script access.');

/**
 * 章节接口
 * 
 * @author 陈蕾
 */
class Controller_Chapter extends Controller_Base
{
	/**
	 * 章节列表
	 */
	public function action_list()
	{
		if (!$this->id) {
			$this->error('未知用户！');
			return;
		}
		
		// 公共章节
		$records = Model_Chapter::getList();
		
		// 需要的列表数据
		$list = array();
		foreach ($records as $record) {
			$list[] = $this->reduceResult($record, array('id', 'name'));
		}
		
		// 总课时统计
		$lesson_stats = Model_Lesson::getStats();
		// 已学课时统计
		$finished_stats = Model_LessonProgress::getStats($this->id);
		
		// 整合统计信息
		foreach ($list as &$chapter) {
			$id = $chapter['id'];
			
			$stats = array(
				'total'    => 0,
				'finished' => 0
			);
			
			if (array_key_exists($id, $lesson_stats)) {
				$stats['total'] = $lesson_stats[$id];
			}
			
			if (array_key_exists($id, $finished_stats)) {
				$stats['finished'] = $finished_stats[$id];
			}
			
			$chapter['stats'] = $stats;
		}
		
		$this->output($list);
	}
	
	/**
	 * 课时列表
	 */
	public function action_lessons()
	{
		// 测试数据
		$this->test(array(
			'chapter_id' => 1
		));
		
		if (!$this->id) {
			$this->error('未知用户！');
			return;
		}
		
		$chapter_id = $this->get('chapter_id');
		if (!$chapter_id) {
			$this->error('请指定你要获取的章节！');
			return;
		}
		
		// 进度信息
		$details = Model_LessonProgress::getProfileByMember($this->id, $chapter_id);
		
		// 课时列表
		$records = Model_Lesson::getListByChapter($chapter_id);
		
		// 整合进度信息
		$list = array();
		foreach ($records as $record) {
			$lesson = $this->reduceResult($record, array('client_id', 'name'));
			
			$id = $record['id'];
			if (array_key_exists($id, $details)) {
				$lesson['progress'] = $details[$id];
			} else {
				$lesson['progress'] = array('state' => 0);
			}
			
			$list[] = $lesson;
		}
		
		$this->output($list);
	}
}